package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.book.biz.UserBiz;
import com.book.biz.impl.UserBizImpl;
import com.book.util.RequestURL;
import com.jspsmart.upload.Request;

public class LoginUserServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		
		String uname = request.getParameter("uname");
		String password = request.getParameter("password");
		String rand = (String)session.getAttribute("rand"); 
		String input = request.getParameter("rand"); 
		if(rand.equals(input)){ 
			UserBiz uBiz = new UserBizImpl();
			int isOk = uBiz.login(uname, password);
			if (isOk>0) {
				request.getSession().setAttribute("uname", uname);
				
				String url = request.getHeader("Referer");
				if("http://localhost:8080/bookonline/login_user.jsp".endsWith(url)){
					response.sendRedirect("SelectBook.do?type=all");
				}else{
					response.sendRedirect(url);
				}
				
			}else{
				request.getRequestDispatcher("error.jsp").forward(request, response);
			} 
		}else{request.getRequestDispatcher("error.jsp").forward(request, response);}
	}

}
